/* vim:set noet ts=4: */
/** 
 * scim-python
 * 
 * Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com>
 *
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * $Id: $
 */

#include "scim-python.h"

#define GETTEXT_PACKAGE "scim-python"
#define SCIM_PYTHON_LOCALEDIR "/usr/share/locale"

using namespace scim;
using namespace std;

static ConfigPointer _scim_config;
static vector <IMEngineFactoryPointer> _python_engine_factorys;

static void
init_scim(void) 
{
	PyObject* m;
	
	m = Py_InitModule3("scim", NULL,
						"SCIM.");
	
	if (m == NULL) {
		PyErr_Print ();
		return;
	}
	
	init_event (m);
	init_engine (m);
	init_factory (m);
	init_attribute (m);
	init_lookup_table (m);
}


extern "C" void
scim_module_init (void)
{
	bindtextdomain (GETTEXT_PACKAGE, SCIM_PYTHON_LOCALEDIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");

	putenv ("PYTHONPATH="SCIM_PYTHON_DATA_DIR);

	Py_Initialize ();
	init_scim ();
}

extern "C" void
scim_module_exit (void)
{
	Py_Finalize ();
}

extern "C" unsigned int 
scim_imengine_module_init (const ConfigPointer &config)
{
	PyObject *pName = NULL;
	PyObject *pModule = NULL;
	PyObject *pFunc = NULL;
	PyObject *pValue = NULL;
	int size = 0;

	_scim_config = config;
	
	pName = PyString_FromString("engines");

	pModule = PyImport_Import(pName);
	Py_DECREF(pName);

	if (pModule == NULL)
		goto _failed_out;
	
	pFunc = PyObject_GetAttrString (pModule, "QueryEngines");
	
	if (pFunc == NULL)
		goto _failed_out;
	
	pValue = PyObject_CallObject(pFunc, NULL);

	if (pValue == NULL)
		goto _failed_out;
	
	if (!PyTuple_Check (pValue))
		goto _failed_out;
	size = PyTuple_Size (pValue);
	for (int i = 0; i < size; i++) {
		PyObject *pFactory;
		pFactory = PyTuple_GetItem(pValue, i);
		_python_engine_factorys.push_back (IMEngineFactoryPointer(PyIMEngineFactory::from_pyobject (pFactory)));
	}

	Py_DECREF(pValue);
	Py_DECREF(pFunc);
	Py_DECREF(pModule);
	return size;
	
_failed_out:
	PyErr_Print ();
	Py_XDECREF(pValue);
	Py_XDECREF(pFunc);
	Py_XDECREF(pModule);
	
	return size;
}

extern "C" IMEngineFactoryPointer 
scim_imengine_module_create_factory (uint32 engine)
{
	if ( engine < 0 || engine >= _python_engine_factorys.size ())
		return IMEngineFactoryPointer (0);

	return _python_engine_factorys[engine];
}

